#include "managementdialog.h"
#include "ui_managementdialog.h"
#include <QDebug>

ManagementDialog::ManagementDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ManagementDialog)
    , databaseManager(nullptr)
    , selectedFeatureId(-1)
    , selectedRuleId(-1)
{
    ui->setupUi(this);
    
    // 初始化数据库连接
    initializeDatabase();
    
    // 设置表格
    setupTables();
    
    // 连接信号槽
    connectSignals();
    
    // 加载数据
    refreshData();
}

ManagementDialog::~ManagementDialog()
{
    delete ui;
    if (databaseManager) {
        delete databaseManager;
    }
}

void ManagementDialog::initializeDatabase()
{
    databaseManager = new DatabaseManager(this);
    if (!databaseManager->openDatabase()) {
        showMessage("数据库错误", "无法连接到数据库！", QMessageBox::Critical);
    }
}

void ManagementDialog::setupTables()
{
    // 设置特征表格
    ui->featuresTableWidget->setColumnCount(2);
    QStringList featureHeaders;
    featureHeaders << "ID" << "特征名称";
    ui->featuresTableWidget->setHorizontalHeaderLabels(featureHeaders);
    ui->featuresTableWidget->horizontalHeader()->setStretchLastSection(true);
    ui->featuresTableWidget->setColumnWidth(0, 80);
    
    // 设置规则表格
    ui->rulesTableWidget->setColumnCount(5);
    QStringList ruleHeaders;
    ruleHeaders << "ID" << "名称" << "类别" << "条件" << "结论";
    ui->rulesTableWidget->setHorizontalHeaderLabels(ruleHeaders);
    ui->rulesTableWidget->horizontalHeader()->setStretchLastSection(true);
    ui->rulesTableWidget->setColumnWidth(0, 80);
    ui->rulesTableWidget->setColumnWidth(1, 150);
    ui->rulesTableWidget->setColumnWidth(2, 150);
    ui->rulesTableWidget->setColumnWidth(3, 300);
}

void ManagementDialog::connectSignals()
{
    // 特征表格选择变化
    connect(ui->featuresTableWidget, &QTableWidget::itemSelectionChanged,
            this, &ManagementDialog::on_featuresTableWidget_itemSelectionChanged);
    
    // 规则表格选择变化
    connect(ui->rulesTableWidget, &QTableWidget::itemSelectionChanged,
            this, &ManagementDialog::on_rulesTableWidget_itemSelectionChanged);
}

void ManagementDialog::loadFeatures()
{
    if (!databaseManager) return;
    
    QList<QPair<int, QString>> features = databaseManager->getAllFeaturesWithId();
    
    ui->featuresTableWidget->setRowCount(features.size());
    
    for (int i = 0; i < features.size(); ++i) {
        QTableWidgetItem *idItem = new QTableWidgetItem(QString::number(features[i].first));
        QTableWidgetItem *nameItem = new QTableWidgetItem(features[i].second);
        
        idItem->setFlags(idItem->flags() & ~Qt::ItemIsEditable);
        
        ui->featuresTableWidget->setItem(i, 0, idItem);
        ui->featuresTableWidget->setItem(i, 1, nameItem);
    }
}

void ManagementDialog::loadRules()
{
    if (!databaseManager) return;
    
    auto rules = databaseManager->getAllRulesWithFullInfo();
    
    ui->rulesTableWidget->setRowCount(rules.size());
    
    for (int i = 0; i < rules.size(); ++i) {
        QTableWidgetItem *idItem = new QTableWidgetItem(QString::number(std::get<0>(rules[i])));
        QTableWidgetItem *nameItem = new QTableWidgetItem(std::get<1>(rules[i]));
        QTableWidgetItem *categoryItem = new QTableWidgetItem(std::get<2>(rules[i]));
        QTableWidgetItem *conditionItem = new QTableWidgetItem(formatRuleConditions(std::get<3>(rules[i])));
        QTableWidgetItem *conclusionItem = new QTableWidgetItem(std::get<4>(rules[i]));
        
        idItem->setFlags(idItem->flags() & ~Qt::ItemIsEditable);
        
        ui->rulesTableWidget->setItem(i, 0, idItem);
        ui->rulesTableWidget->setItem(i, 1, nameItem);
        ui->rulesTableWidget->setItem(i, 2, categoryItem);
        ui->rulesTableWidget->setItem(i, 3, conditionItem);
        ui->rulesTableWidget->setItem(i, 4, conclusionItem);
    }
}

void ManagementDialog::refreshData()
{
    loadFeatures();
    loadRules();
    clearFeatureInputs();
    clearRuleInputs();
}

// 特征管理槽函数
void ManagementDialog::on_addFeatureButton_clicked()
{
    addFeature();
}

void ManagementDialog::on_updateFeatureButton_clicked()
{
    updateFeature();
}

void ManagementDialog::on_deleteFeatureButton_clicked()
{
    deleteFeature();
}

void ManagementDialog::on_featuresTableWidget_itemSelectionChanged()
{
    QList<QTableWidgetItem*> selectedItems = ui->featuresTableWidget->selectedItems();
    if (!selectedItems.isEmpty()) {
        int row = selectedItems.first()->row();
        QTableWidgetItem *idItem = ui->featuresTableWidget->item(row, 0);
        QTableWidgetItem *nameItem = ui->featuresTableWidget->item(row, 1);
        
        if (idItem && nameItem) {
            selectedFeatureId = idItem->text().toInt();
            ui->featureNameLineEdit->setText(nameItem->text());
        }
    } else {
        selectedFeatureId = -1;
        clearFeatureInputs();
    }
}

// 规则管理槽函数
void ManagementDialog::on_addRuleButton_clicked()
{
    addRule();
}

void ManagementDialog::on_updateRuleButton_clicked()
{
    updateRule();
}

void ManagementDialog::on_deleteRuleButton_clicked()
{
    deleteRule();
}

void ManagementDialog::on_rulesTableWidget_itemSelectionChanged()
{
    QList<QTableWidgetItem*> selectedItems = ui->rulesTableWidget->selectedItems();
    if (!selectedItems.isEmpty()) {
        int row = selectedItems.first()->row();
        QTableWidgetItem *idItem = ui->rulesTableWidget->item(row, 0);
        QTableWidgetItem *nameItem = ui->rulesTableWidget->item(row, 1);
        QTableWidgetItem *categoryItem = ui->rulesTableWidget->item(row, 2);
        QTableWidgetItem *conditionItem = ui->rulesTableWidget->item(row, 3);
        QTableWidgetItem *conclusionItem = ui->rulesTableWidget->item(row, 4);
        
        if (idItem && nameItem && categoryItem && conditionItem && conclusionItem) {
            selectedRuleId = idItem->text().toInt();
            ui->ruleNameLineEdit->setText(nameItem->text());
            ui->ruleCategoryLineEdit->setText(categoryItem->text());
            ui->ruleConditionLineEdit->setText(conditionItem->text());
            ui->ruleConclusionLineEdit->setText(conclusionItem->text());
        }
    } else {
        selectedRuleId = -1;
        clearRuleInputs();
    }
}

// 通用槽函数
void ManagementDialog::on_refreshButton_clicked()
{
    refreshData();
}

void ManagementDialog::on_closeButton_clicked()
{
    accept();
}

// 特征管理函数
void ManagementDialog::addFeature()
{
    if (!validateFeatureInput()) return;
    
    QString featureName = ui->featureNameLineEdit->text().trimmed();
    
    if (databaseManager->addFeature(featureName)) {
        showMessage("成功", "特征添加成功！");
        loadFeatures();
        clearFeatureInputs();
    } else {
        showMessage("错误", "特征添加失败！", QMessageBox::Critical);
    }
}

void ManagementDialog::updateFeature()
{
    if (selectedFeatureId == -1) {
        showMessage("提示", "请先选择要更新的特征！", QMessageBox::Warning);
        return;
    }
    
    if (!validateFeatureInput()) return;
    
    QString featureName = ui->featureNameLineEdit->text().trimmed();
    
    if (databaseManager->updateFeature(selectedFeatureId, featureName)) {
        showMessage("成功", "特征更新成功！");
        loadFeatures();
        clearFeatureInputs();
    } else {
        showMessage("错误", "特征更新失败！", QMessageBox::Critical);
    }
}

void ManagementDialog::deleteFeature()
{
    if (selectedFeatureId == -1) {
        showMessage("提示", "请先选择要删除的特征！", QMessageBox::Warning);
        return;
    }
    
    QMessageBox::StandardButton reply = QMessageBox::question(this, "确认删除", 
        "确定要删除选中的特征吗？", 
        QMessageBox::Yes | QMessageBox::No);
    
    if (reply == QMessageBox::Yes) {
        if (databaseManager->deleteFeature(selectedFeatureId)) {
            showMessage("成功", "特征删除成功！");
            loadFeatures();
            clearFeatureInputs();
        } else {
            showMessage("错误", "特征删除失败！", QMessageBox::Critical);
        }
    }
}

void ManagementDialog::clearFeatureInputs()
{
    ui->featureNameLineEdit->clear();
    selectedFeatureId = -1;
}

// 规则管理函数
void ManagementDialog::addRule()
{
    if (!validateRuleInput()) return;
    
    QString ruleName = ui->ruleNameLineEdit->text().trimmed();
    QString category = ui->ruleCategoryLineEdit->text().trimmed();
    QStringList conditions = parseRuleConditions(ui->ruleConditionLineEdit->text().trimmed());
    QString conclusion = ui->ruleConclusionLineEdit->text().trimmed();
    
    if (databaseManager->addRule(ruleName, category, conditions, conclusion)) {
        showMessage("成功", "规则添加成功！");
        loadRules();
        clearRuleInputs();
    } else {
        QString errorMsg = "规则添加失败！\n错误详情: " + databaseManager->lastError();
        showMessage("错误", errorMsg, QMessageBox::Critical);
    }
}

void ManagementDialog::updateRule()
{
    if (selectedRuleId == -1) {
        showMessage("提示", "请先选择要更新的规则！", QMessageBox::Warning);
        return;
    }
    
    if (!validateRuleInput()) return;
    
    QString name = ui->ruleNameLineEdit->text().trimmed();
    QString category = ui->ruleCategoryLineEdit->text().trimmed();
    QStringList conditions = parseRuleConditions(ui->ruleConditionLineEdit->text().trimmed());
    QString conclusion = ui->ruleConclusionLineEdit->text().trimmed();
    
    if (databaseManager->updateRule(selectedRuleId, name, category, conditions, conclusion)) {
        showMessage("成功", "规则更新成功！");
        loadRules();
        clearRuleInputs();
    } else {
        showMessage("错误", "规则更新失败！", QMessageBox::Critical);
    }
}

void ManagementDialog::deleteRule()
{
    if (selectedRuleId == -1) {
        showMessage("提示", "请先选择要删除的规则！", QMessageBox::Warning);
        return;
    }
    
    QMessageBox::StandardButton reply = QMessageBox::question(this, "确认删除", 
        "确定要删除选中的规则吗？", 
        QMessageBox::Yes | QMessageBox::No);
    
    if (reply == QMessageBox::Yes) {
        if (databaseManager->deleteRule(selectedRuleId)) {
            showMessage("成功", "规则删除成功！");
            loadRules();
            clearRuleInputs();
        } else {
            showMessage("错误", "规则删除失败！", QMessageBox::Critical);
        }
    }
}

void ManagementDialog::clearRuleInputs()
{
    ui->ruleNameLineEdit->clear();
    ui->ruleCategoryLineEdit->clear();
    ui->ruleConditionLineEdit->clear();
    ui->ruleConclusionLineEdit->clear();
    selectedRuleId = -1;
}

// 工具函数
void ManagementDialog::showMessage(const QString &title, const QString &message, QMessageBox::Icon icon)
{
    QMessageBox msgBox(this);
    msgBox.setWindowTitle(title);
    msgBox.setText(message);
    msgBox.setIcon(icon);
    msgBox.exec();
}

bool ManagementDialog::validateFeatureInput()
{
    QString featureName = ui->featureNameLineEdit->text().trimmed();
    if (featureName.isEmpty()) {
        showMessage("输入错误", "特征名称不能为空！", QMessageBox::Warning);
        return false;
    }
    return true;
}

bool ManagementDialog::validateRuleInput()
{
    QString ruleName = ui->ruleNameLineEdit->text().trimmed();
    QString category = ui->ruleCategoryLineEdit->text().trimmed();
    QString conditions = ui->ruleConditionLineEdit->text().trimmed();
    QString conclusion = ui->ruleConclusionLineEdit->text().trimmed();
    
    if (ruleName.isEmpty()) {
        showMessage("输入错误", "规则名称不能为空！", QMessageBox::Warning);
        return false;
    }
    
    if (category.isEmpty()) {
        showMessage("输入错误", "规则类别不能为空！", QMessageBox::Warning);
        return false;
    }
    
    if (conditions.isEmpty()) {
        showMessage("输入错误", "规则条件不能为空！", QMessageBox::Warning);
        return false;
    }
    
    if (conclusion.isEmpty()) {
        showMessage("输入错误", "规则结论不能为空！", QMessageBox::Warning);
        return false;
    }
    
    return true;
}

QStringList ManagementDialog::parseRuleConditions(const QString &conditionsText)
{
    QStringList conditions = conditionsText.split(",", Qt::SkipEmptyParts);
    for (QString &condition : conditions) {
        condition = condition.trimmed();
    }
    return conditions;
}

QString ManagementDialog::formatRuleConditions(const QStringList &conditions)
{
    return conditions.join(", ");
}